<?php
namespace app\service;
// +----------------------------------------------------------------------
// | bbcThink
// +----------------------------------------------------------------------
// | Copyright (c) 2025 http://bbcweb.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: bbcweb <22745529@qq.com>
// +----------------------------------------------------------------------
use think\facade\Db;

/**
 * 数据库操作服务层
 */
class DbHelper
{
    public static function init($p)
    {
        Db::name('admin')->insert(['username'=>$p['username'],'login_pwd'=>md5($p['password']),'add_time'=>time(),'token'=>md5(time())]);
        Db::name('country')->insert(['name'=>'中文','ename'=>'zh-cn','icon'=>'/images/country/zh-cn.png']);
    }
    public static function row($param)
    {
        $param['where']=isset($param['where'])?$param['where']:[];
        return Db::name($param['table'])->where($param['where'])->find();
    }
    public static function one($param)
    {
        $param['where']=isset($param['where'])?$param['where']:[];
        return Db::name($param['table'])->where($param['where'])->value($param['column']);
    }
    public static function query($param)
    {
        $param['field']=isset($param['field'])?$param['field']:'*';
        $param['where']=isset($param['where'])?$param['where']:[];
        $param['order']=isset($param['order'])?$param['order']:'id desc';
        $appname=isset($param['appname'])?$param['appname']:'mysql';
        return Db::connect($appname)->name($param['table'])->where($param['where'])->field($param['field'])->order($param['order'])->select()->ToArray();
    }
    
    public static function paginate($param)
    {
        $param['pagesize']=isset($param['pagesize'])?$param['pagesize']:20;
        $param['query']=isset($param['query'])?$param['query']:'';
        $param['field']=isset($param['field'])?$param['field']:'*';
        return Db::name($param['table'])->where($param['where'])->field($param['field'])->paginate(['list_row'=>$param['pagesize'],'query'=>$param['query']]);
    }
    
    public static function delete($param)
    {
        return Db::name($param['table'])->where($param['where'])->delete();
    }
    
    public static function count($param)
    {
        return Db::name($param['table'])->where($param['where'])->count();
    }
    
    public static function update($param)
    {
        return Db::name($param['table'])->where($param['where'])->update($param['data']);
    }
    
    public static function insert($param)
    {
        return Db::name($param['table'])->insertGetId($param['data']);
    }
}